import json
import logging

import requests
from odoo import _, api, fields, models
from odoo.exceptions import AccessDenied, ValidationError

_logger = logging.getLogger(__name__)


class ResUsers(models.Model):
    _inherit = 'res.users'

    @api.model
    def _auth_oauth_rpc(self, endpoint, access_token):
        if 'weixin' in endpoint:
            return requests.get(endpoint, params={'code': access_token}).json()
        else:
            return requests.get(endpoint, params={'access_token': access_token}).json()
    
    @api.model
    def auth_oauth(self, provider, params):
        # 验证身份
        provider = int(provider) # 转换格式
        access_token = params.get('access_token')
        validation = self._auth_oauth_validate(provider, access_token)
        if 'unionid' in validation:
            validation["user_id"] = validation["unionid"]
        # 检查必要参数
        if not validation.get('user_id'):
            # 当没有user_id，将id认为user_id
            if validation.get('id'):
                validation['user_id'] = validation['id']
            else:
                raise AccessDenied()
        # 检查登录用户
        login = self._auth_oauth_signin(provider, validation, params)
        if not login:
            raise AccessDenied()
        # 返回用户凭证
        return (self.env.cr.dbname, login, access_token)
